//
//  HCScrollTitleView.swift
//  HappyComics
//
//  Created by 金玉龙 on 15/11/24.
//  Copyright © 2015年 jinyulong. All rights reserved.
//

import UIKit

protocol HCScrollTitleViewDelegate : NSObjectProtocol{
    func titleView(scrollTitleView : HCScrollTitleView ,didSelectedIndex index : Int) ->Void
}

class HCScrollTitleView: UIView {
    var selectedIndex : Int?
    var titlesArray : NSArray?
    var constraintsArray : NSMutableArray = NSMutableArray();
    
    var indicateLine : UIView = UIView()
    var buttonArray : NSMutableArray = NSMutableArray()
//MARK: title color
    var defaultTitleColor : UIColor = UIColor.blackColor()
    var selectedTitleColor : UIColor = UIColor.blueColor()
//MARK: title font
    var defaultTitleFont : UIFont = UIFont.systemFontOfSize(15.0)
    var selectedTitleFont : UIFont = UIFont.systemFontOfSize(18.0)
//MARK: background color
    var defaultBackgroundColor : UIColor = UIColor.whiteColor()
    var selectedBackgroundColor : UIColor = UIColor.whiteColor()
//MARK: button layer
    var btnBorderColor : UIColor = UIColor.clearColor()
    var btnBorderWidth : CGFloat = 0.0
    weak internal var delegate : HCScrollTitleViewDelegate?

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initWithTitleArray(titleArray : NSArray?  ,selectedIndex buttonTag : Int?) ->Void{
        self.backgroundColor = UIColor.whiteColor()
        self.titlesArray = NSArray.init(array: titleArray!)
        if titleArray?.count > 0 && titleArray! .isKindOfClass(NSArray) {
            for title in titleArray! {
                let titleButton = UIButton.init(type: UIButtonType.Custom)
                let titleStr = title as? String
                titleButton.setTitle(titleStr, forState: UIControlState.Normal)
                titleButton.titleLabel?.font = defaultTitleFont
                titleButton.setTitleColor(selectedTitleColor, forState: UIControlState.Selected)
                titleButton.setTitleColor(defaultTitleColor, forState: UIControlState.Normal)
                titleButton.tag = 100 + (titlesArray?.indexOfObject(title))!
                titleButton .addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
                buttonArray.addObject(titleButton);
                self.addSubview(titleButton)
            }
        }
        selectedIndex = buttonTag
        self.layout()
        self.selectedAtIndex(buttonTag!)
    }
    func layout() ->Void{
        var lastButton : UIButton? = nil;
        for button in buttonArray {
            let masButton = button as! UIButton
            masButton.snp_makeConstraints(closure: { (make) -> Void in
                self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[masButton]|", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: nil , views: ["masButton":masButton]))
            })
            if lastButton == nil{
                self.addConstraint(NSLayoutConstraint.init(item: masButton, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0))
            }else{
                self.addConstraint(NSLayoutConstraint.init(item: masButton, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: lastButton, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0))
                self.addConstraint(NSLayoutConstraint.init(item: masButton, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: lastButton, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0))
            }
            lastButton = masButton
        }
        self.addConstraint(NSLayoutConstraint.init(item: lastButton!, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0))
        self .layoutIfNeeded()
        self .addSubview(indicateLine)
        indicateLine.backgroundColor = selectedTitleColor
    }
    
    func buttonClick(button : UIButton) ->Void{
        self.selectedAtIndex(button.tag - 100)
        delegate?.titleView(self, didSelectedIndex: button.tag - 100)
    }
    
    func selectedAtIndex(index : Int) ->Void{
        if  buttonArray.count > 0 {
            for buttonTmp in buttonArray{
                let titleButton = buttonTmp as! UIButton
                if titleButton.tag - 100 == index {
                    titleButton.selected = true
                    titleButton.userInteractionEnabled = false
                    self .updateIndictWithSelectedButton(titleButton)
                }else {
                    titleButton.selected = false
                    titleButton.userInteractionEnabled = true
                    titleButton.titleLabel?.font = defaultTitleFont
                }
            }
        }
    }
    
    func updateIndictWithSelectedButton( button : UIButton){
        unowned let weakSelf = self
        UIView.animateWithDuration(0.3, animations: { () -> Void in
//MARK: update bottomLine position
            self.indicateLine.snp_remakeConstraints(closure: { (make) -> Void in
                make.bottom.equalTo(button.snp_bottom)
                make.left.equalTo(button.snp_left).offset(5)
                make.right.equalTo(button.snp_right).offset(-5)
                make.height.equalTo(3)
            })
            button.titleLabel?.font = weakSelf.selectedTitleFont
            weakSelf.layoutIfNeeded()
            }, completion: nil)
    }
    
    func updateButtonPropertys() ->Void{
        if  buttonArray.count > 0{
            for buttonTmp in buttonArray{
                let button = buttonTmp as! UIButton
                button.setTitleColor(selectedTitleColor, forState: UIControlState.Selected)
                button.setTitleColor(defaultTitleColor, forState: UIControlState.Normal)
                if button.selected {
                    button.backgroundColor = selectedBackgroundColor
                }else{
                    button.backgroundColor = defaultBackgroundColor
                }
                button.layer.borderColor = btnBorderColor.CGColor
                button.layer.borderWidth = btnBorderWidth
            }
        }
    }
}
